<template>
  <a-modal title="关联模型" width="900px" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <div class="table">
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        rowKey="modelId"
        bordered
        :pagination="false"
        :customRow="customRow"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      >
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex === 'subscribeTopic'">
            <a-tooltip>
              <template #title>{{ record.subscribeTopic }}</template>
              <div class="subscribeTopic">{{ record.subscribeTopic }}</div>
            </a-tooltip>
          </template>
          <template v-if="column.dataIndex === 'isEnable'">
            {{ record.isEnable ? '启用' : '禁用' }}
          </template>
        </template>
      </a-table>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { reactive, ref, nextTick, onMounted } from 'vue';
  import { defineProps } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { iotApi } from '/@/api/plat/deviceDataModel';
  import { iotApi as iotModelaApi } from '/@/api/plat/dataModel';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { PageMixin } from '/@/utils/mixin';
  import { connectTypeDict } from '/@/assets/js/dict';
  const { resetForm } = PageMixin();

  const emits = defineEmits(['reloadList']);

  // 是否显示
  const visibleFlag = ref(false);
  const tableData = ref([]);
  const columns = ref([
    {
      title: '数据模型代码',
      dataIndex: 'modelCode',
    },
    {
      title: '数据模型名称',
      dataIndex: 'modelName',
      width: 130,
    },
    {
      title: '订阅主题',
      dataIndex: 'subscribeTopic',
    },
    {
      title: '是否启用',
      dataIndex: 'isEnable',
      width: 80,
    },
  ]);
  const selectedRowKeyList = ref([]);
  let deviceId = null;

  function show(rowData) {
    deviceId = rowData.deviceId;
    iotApi.queryList({ deviceId }).then(({ data }) => {
      selectedRowKeyList.value = data.map((m) => m.modelId);
    });
    visibleFlag.value = true;
    iotModelaApi.queryList().then(({ data }) => {
      tableData.value = data;
    });
  }

  function onClose() {
    selectedRowKeyList.value = [];
    visibleFlag.value = false;
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      const form = {
        deviceId: deviceId,
        modelList: selectedRowKeyList.value,
      };
      iotApi.bindModels(form).then(({ data }) => {
        if (!data) {
          message.error('操作失败，请检查参数是否完整');
        } else {
          message.success('操作成功');
          emits('reloadList');
          onClose();
        }
      });
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  // 每一行绑定点击事件
  const customRow = (record, index) => {
    return {
      onClick: () => {
        onSelectChange(null, [record]);
      },
    };
  };

  // 列选择
  function onSelectChange(selectedRowKeys, selectedRows) {
    if (selectedRows.length > 0) {
      const modelId = selectedRows[0].modelId;
      const index = selectedRowKeyList.value.findIndex((m) => m === modelId);
      if (index >= 0) {
        selectedRowKeyList.value.splice(index, 1);
      } else {
        selectedRowKeyList.value.push(modelId);
      }
    }
  }

  defineExpose({
    show,
  });
</script>

<style scoped>
  .subscribeTopic {
    width: 250px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
  }
</style>
